from PySide6.QtCore import Slot, Qt, Signal
from PySide6.QtWidgets import QDialog, QTableWidgetItem
from PySide6.QtNetwork import QNetworkInterface
from Communicate.DeviceScanner import DeviceScanner
from Devices.Device import Device, ChiotDevice, AndlinkDevice

from Forms.ScanDeviceWindow_UI import Ui_FormScanDevice

class ScanDeviceWindow(QDialog, Ui_FormScanDevice):
    ConnectDevice = Signal(Device)

    def __init__(self, parent = None):
        super().__init__()
        self.setupUi(self)

        flags = self.windowFlags()
        self.setWindowFlags(flags & ~Qt.WindowContextHelpButtonHint)

        self.tableWidget_Devices.setColumnWidth(0, 120)
        self.tableWidget_Devices.setColumnWidth(1, 150)
        self.tableWidget_Devices.setColumnWidth(2, 80)
        self.tableWidget_Devices.setColumnWidth(3, 80)

        self.__UdpScanner = DeviceScanner()
        self.__UdpScanner.DeviceOnline.connect(self.on_DeviceOnline)
        self.__UdpScanner.started.connect(self.on_DeviceScanStarted)
        self.__UdpScanner.finished.connect(self.on_DeviceScanFinished)

    def Init(self):
        self.comboBox_DeviceType.clear()
        last_ip = self.comboBox_IP.currentText();
        self.comboBox_IP.clear()

        displayNameList = Device.GetSupportDeviceDisplayNameList()
        self.comboBox_DeviceType.addItems(displayNameList)

        list = QNetworkInterface.allAddresses()
        for address in list:
            if (address.protocol() == address.IPv4Protocol and "127.0.0.1" != address.toString()):
                ip = address.toString()
                ips = ip.split('.')
                self.comboBox_IP.addItem(f"{ips[0]:>3}.{ips[1]:>3}.{ips[2]:>3}.")
            
        for i in range(self.comboBox_IP.count()):
            txt = self.comboBox_IP.itemText(i)
            if (txt in last_ip):
                self.comboBox_IP.setCurrentText(last_ip)
                break

    @Slot()
    def on_pushButton_Search_clicked(self):
        self.tableWidget_Devices.setRowCount(0)
        self.tableWidget_Devices.setFocus(Qt.TabFocusReason)
        if (~self.__UdpScanner.isRunning()):
            self.__UdpScanner.start()

    @Slot()
    def on_pushButton_Connect_clicked(self):
        ip:str = self.comboBox_IP.currentText().replace(" ", "")
        cmdPort:str = self.lineEdit_CmdPort.text().replace(" ", "")
        logPort:str = self.lineEdit_LogPort.text().replace(" ", "")
        if (0 != len(ip)):
            scd = Device.GetSupportChiotDeviceByDisplayName(self.comboBox_DeviceType.currentText())
            if (not scd is None):
                if (0 != len(cmdPort) and 0 != len(logPort)):
                    device = ChiotDevice(ip, self.comboBox_DeviceType.currentText(), int(cmdPort), int(logPort), "")
                    self.ConnectDevice.emit(device)
            else:
                sad = Device.GetSupportAndlinkDeviceByDisplayName(self.comboBox_DeviceType.currentText())
                if (not sad is None):
                    device = AndlinkDevice(ip, self.comboBox_DeviceType.currentText(), "")
                    self.ConnectDevice.emit(device)
                    
    @Slot(QTableWidgetItem)
    def on_tableWidget_Devices_itemDoubleClicked(self, item):
        curRow = item.row()

        ip = self.tableWidget_Devices.item(curRow, 0).text()
        type = self.tableWidget_Devices.item(curRow, 1).text()
        cmdPort = self.tableWidget_Devices.item(curRow, 2).text()
        logPort = self.tableWidget_Devices.item(curRow, 3).text()
        mac = self.tableWidget_Devices.item(curRow, 4).text()

        if (0 == len(cmdPort) or 0 == len(logPort)):
            device = AndlinkDevice(ip, type, mac)
            self.ConnectDevice.emit(device)
        else:
            device = ChiotDevice(ip, type, int(cmdPort), int(logPort), mac)
            self.ConnectDevice.emit(device)

    def on_DeviceOnline(self, device):
        currentRow = -1
        for i in range(self.tableWidget_Devices.rowCount()):
            ip = self.tableWidget_Devices.item(i, 0).text()
            #如果是同一个设备，则判断是否支持更强功能
            if (device.GetIP() == ip):
                cmdPort = self.tableWidget_Devices.item(i, 2).text()
                logPort = self.tableWidget_Devices.item(i, 3).text()

                #如果设备是ChiotDevice设备，则表示是新设备，需要检测是否需要更新列表
                #如果当前设备支持端口，则表示是新设备，不需要更新
                if (type(device) == ChiotDevice and 0 == len(cmdPort) and 0 == len(logPort)):
                    currentRow = i
                    break
                else:
                    return

        if (currentRow < 0):
            currentRow = self.tableWidget_Devices.rowCount()
            self.tableWidget_Devices.insertRow(currentRow)

        self.tableWidget_Devices.setItem(currentRow, 0, QTableWidgetItem(device.GetIP()))
        self.tableWidget_Devices.setItem(currentRow, 1, QTableWidgetItem(device.GetDisplayName()))
        self.tableWidget_Devices.setItem(currentRow, 2, QTableWidgetItem(""))
        self.tableWidget_Devices.setItem(currentRow, 3, QTableWidgetItem(""))
        self.tableWidget_Devices.setItem(currentRow, 4, QTableWidgetItem(device.GetMAC()))

        if (ChiotDevice == type(device)):
            self.tableWidget_Devices.setItem(currentRow, 2, QTableWidgetItem(device.getCmdPort()))
            self.tableWidget_Devices.setItem(currentRow, 3, QTableWidgetItem(device.getLogPort()))

    def on_DeviceScanStarted(self):
        self.pushButton_Search.setEnabled(False)

    def on_DeviceScanFinished(self):
        self.pushButton_Search.setEnabled(True)

